package com.mes.basicdata.service;

import java.util.Collection;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.dao.iface.IDeptDao;
import com.mes.basicdata.dao.iface.IEmployeeDao;
import com.mes.basicdata.domain.Dept;
import com.mes.basicdata.domain.Employee;
import com.mes.basicdata.manager.DeptManager;
import com.mes.basicdata.manager.iface.IDeptManager;
import com.mes.common.service.BasicService;

@Service
public class DeptService extends BasicService<Dept>{

	@Autowired
	private IDeptDao deptDao;
	
	@Autowired
	private IEmployeeDao employeeDao;
	
	@Autowired
	private IDeptManager deptManager;
	

	//获得子部门
	@DataProvider
	public Collection<Dept> getChildDepts(String parentDeptId) throws Exception{
		 
		Collection<Dept> depts = deptDao.findByProperty("parentDeptUid", parentDeptId);
		return depts;
	}
	
	//根据id查询部门
	@DataProvider
	public Dept getDeptById(String id){
		try {
			return deptDao.getById(id);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@DataProvider
	public Collection<Dept> getDepts(String parentDeptId) throws Exception{
		Collection<Dept> depts = deptDao.findByProperty("parentDeptUid", parentDeptId);
		
		return depts;
	}
	
	//查询Dept的名称
	@DataProvider
	public String getDeptName(String deptUid) throws Exception{
		return deptDao.getDeptName(deptUid);
	}
	
	@DataProvider
    public void getDepts(Page<Dept> page, Map<String, Object> parameter) throws Exception{
    	if (parameter != null && !parameter.equals("") ){	
    			deptDao.getDepts(page, parameter);
    	}
			
    	
    }
	//查询厂家
	@DataProvider
	public Collection<Dept> getFactory(String deptType) throws Exception{
		return deptDao.findByProperty("deptType", deptType,"deptType");
	}
	
	/**
	 * 获得当前登录人员所在部门
	 * @return
	 * @throws Exception 
	 */
	@DataProvider
	public Collection<Dept> getDeptbyLoginUser() throws Exception{
		String username = ContextHolder.getLoginUser().getUsername();
		Employee employee = employeeDao.getById(username);
		
		return deptDao.findByProperty("deptUid", employee.getDeptUid());
	}
	
	@DataResolver
	public void saveDept(Map<String, Collection<Dept>> dataItems) throws Exception{
		deptManager.saveDept(dataItems);
	}
	@Expose
	public String getDeptIdbyLoginUser() throws Exception{
		String username = ContextHolder.getLoginUser().getUsername();
		Employee employee = employeeDao.getById(username);
		
		return employee.getDeptUid();
	}
}
